

#include "mymesh.h"


#include <vcg/complex/trimesh/clean.h>


/*include the algorihm that update bounding box and normals*/
#include <vcg/complex/trimesh/update/bounding.h>
#include <vcg/complex/trimesh/update/normal.h>
#include <vcg/complex/trimesh/allocate.h>

#include <wrap/io_trimesh/import.h>
#include <wrap/io_trimesh/export_ply.h>
#include <wrap/io_trimesh/export_off.h>

#include <GL/glew.h>
#include <wrap/gl/trimesh.h>



 

void CMesh::FlipX(){
  for (int i=0; i<vert.size(); i++) vert[i].P().X()*=-1;
}

void  CMesh::ColorQ(float scale){
    for (int i=0; i<face.size(); i++) {
      int k = ( face[i].IsAnyF() )? 255:0; 
      face[i].C() = vcg::Color4b( 255,k, int(255*face[i].Q()/scale) , 255);
    }
} 

void  CMesh::ColorByQ(int q){
    for (int i=0; i<face.size(); i++) {
      if (int(face[i].Q())==q) 
      face[i].C() = vcg::Color4b( 255,255,0 , 255);
      else
      face[i].C() = vcg::Color4b( 255,255,255 , 255);
    } 
}

void  CMesh::ResetQ(){
    for (int i=0; i<face.size(); i++) face[i].Q()=1;
}

bool CMesh::Save(char *meshFilename) {
	if(   
    vcg::tri::io::ExporterOFF<CMesh>::Save(*this,meshFilename, vcg::tri::io::Mask::IOM_BITPOLYGONAL )!=0
  ) 
  {  
      fprintf(stderr,"Error saving file %s\n",meshFilename);
		  return false;
  }
  return true;
  
}

void CMesh::Compact(){
  vcg::tri::Clean<CMesh>::RemoveUnreferencedVertex(*this);
  vcg::tri::Allocator<CMesh>::CompactVertexVector(*this);
  vcg::tri::Allocator<CMesh>::CompactFaceVector(*this);
}

bool CMesh::Load(char *meshFilename) {
  Clear();
  
	if(  
    vcg::tri::io::Importer<CMesh>::Open(*this,meshFilename)!=0
  ) 
  {
      fprintf(stderr,"Error reading file %s\n",meshFilename);
		  return false;
  }
  fprintf(stderr,"Load %s (%d)\n",meshFilename, fn);
  
  vcg::tri::UpdateTopology<CMesh>::FaceFace(*this);
  
  
  // Initialize the mesh itself
	vcg::tri::UpdateBounding<CMesh>::Box(*this);      // update bounding box
  //vcg::tri::UpdateNormals<CMesh>::PerVertexNormalizePerFaceNormalized(mesh); // update Normals
  vcg::tri::UpdateNormals<CMesh>::PerVertexPerFace(*this); // update Normals
  
  return true;
}


